<template>
  <ul class="list">
      <li class="item" 
        v-for="item of letters" 
        :key="item"
        :ref="item"
        @touchstart="handelTouchStart"
        @touchmove="handelTouchMove"
        @touchend="handelTouchEnd"
        @click="hanleLetterClick"
      >
        {{item}}
      </li>
  </ul>
</template>

<script>
export default {
  name: "CityAlphabet",
  props: {
    cities: Object
  },
  computed:{
    letters () {
      const letters=[]
      for (let i in this.cities){
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false,
      startY:0,
      timer:null//节流
    }
  },
  updated () {
    this.startY=this.$refs['A'][0].offsetTop
  },
  methods :{
    //向外传递点击事件
    hanleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    //字母表滑动开始事件
    handelTouchStart () {
      this.touchStatus=true
    },
    //字母表滑动过程事件
    handelTouchMove (e) {
      if(this.touchStatus){ 
        // 节流
        if(this.timer){
          clearTimeout(this.timer)
        } 
        //字母表滑动算法
        this.timer=setTimeout(() => {
          const startY=this.$refs['A'][0].offsetTop
          const touchY=e.touches[0].clientY -69
          const index =Math.floor((touchY-this.startY) / 20)
          if(index >=0 && index < this.letters.length){
            this.$emit('change',this.letters[index])
          }
        }, 16)
      }
    },
    //字母表滑动结束事件
    handelTouchEnd () {
      this.touchStatus=false
    }
  }
}
</script>

<style scoped>
.list{
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    top: 1.58rem;
    bottom: 0;
    right: 0;
    width: .4rem;
}
.item{
    line-height: .4rem;
    text-align: center;
    color: #00bcd4;
}
</style>